package cn.test.client;

import cn.test.domain.Heart;
import cn.test.domain.User;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import jdk.internal.org.objectweb.asm.Handle;
import lombok.extern.slf4j.Slf4j;

/***
 *
 *
 * @Author: SJie
 * Date: 2019/12/19 下午5:44
 * Description: 
 *
 */

public class ClientHandler2 extends SimpleChannelInboundHandler {
    int readIdleTimes = 0;
    protected void channelRead0(ChannelHandlerContext ctx, Object o) throws Exception {
        System.out.println("channelRead2");
        ctx.channel().writeAndFlush(new User());
//        readIdleTimes = 0;
//        if (o instanceof Heart) {
//            if ("heart".equals(((Heart) o).getTest())) {
//                System.out.println("heart");
//                return;
//            }
//        }
//        ctx.fireChannelRead(o);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("关闭连接");
        ClientMain.doconnect();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent)evt;

        String eventType = null;
        switch (event.state()){
            case READER_IDLE:
                eventType = "client:读空闲";
                readIdleTimes ++; // 读空闲的计数加1
                break;
            case WRITER_IDLE:
                eventType = "client:写空闲";
                ctx.writeAndFlush(new Heart());
                break;
            case ALL_IDLE:
                eventType ="client:读写空闲";
// 不处理
                break;
        }
        //System.out.println(ctx.channel().remoteAddress() + "超时事件：" +eventType);
        if(readIdleTimes > 4){
            //System.out.println(" [server]读空闲超过3次，关闭连接");
            ctx.channel().writeAndFlush("you are out");
            ctx.channel().close();
            ClientMain.doconnect();
        }
        //System.out.println("readIdleTimes:"+readIdleTimes);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
